<script setup lang="ts">
import {ref, watch, markRaw, shallowRef, defineAsyncComponent} from 'vue'
import type {Component} from 'vue'

import CustomIcon from '@/components/CustomIcon'


const configs = [
  {
    key: 'storage',
    title: '存储设置',
    icon: 'fluent-FolderOpen20Filled',
    iconSize: 24,
    desc: '设置存储配置(含云存储)'
  },
  {
    key: 'agreements',
    title: '政策协议',
    icon: 'fluent-NotepadPerson24Filled',
    iconSize: 24,
    desc: '设置各项政策协议'
  },
  {
    key: 'wechat',
    title: '微信小程序',
    icon: 'carbon-LogoWechat',
    iconSize: 28,
    desc: '设置小程序各项配置'
  },
  {
    key: 'payment',
    title: '支付设置',
    icon: 'fluent-Payment24Filled',
    iconSize: 28,
    desc: '设置支付配置'
  },
  {
    key: 'withdrawal',
    title: '会员提现',
    icon: 'fa-MoneyCheck',
    iconSize: 24,
    desc: '设置会员提现配置'
  },
  {
    key: 'userSettings',
    title: '用户设置',
    icon: 'fa-UsersCog',
    iconSize: 26,
    desc: '配置用户各项设置'
  }
]

//组件
const components = ref<string | null>(null)
// 使用 shallowRef 来存储组件
const currentComponent = shallowRef<Component | null>(null)
const componentMap: Record<string, Component> = {
  storage: defineAsyncComponent(() => import('./components/storageConfig.vue')),
  agreements: defineAsyncComponent(() => import('./components/agreementConfig.vue')),
  wechat: defineAsyncComponent(() => import('./components/weChatConfig.vue')),
}

// 加载组件
function loadComponent(key: string) {
  if (!key || !(key in componentMap)) {
    currentComponent.value = null
    return
  }
  currentComponent.value = markRaw(componentMap[key])
}

// 监听组件变化
watch(components, async (newKey) => {
  if (newKey) {
    loadComponent(newKey)
  } else {
    currentComponent.value = null
  }
})

</script>

<template>
  <div>
    <n-grid cols="3 s:3 m:3 l:4 xl:5 2xl:7" responsive="screen" style="gap: 8px;">
      <template v-for="(item,index) in configs" :key="index">
        <n-grid-item>
          <n-card>
            <div style="display: flex;justify-content:space-between;">
              <div>
                <h3 style="display: flex; align-items: center;">
                  <custom-icon :component="item.icon" :size="item.iconSize" style="padding-right: 8px;"/>
                  {{ item.title }}
                </h3>
                <div>
                  {{ item.desc }}
                </div>
              </div>
              <div style="display: flex; align-items: end;">
                <n-button tertiary type="primary" size="small" style="position: relative;bottom: 0"
                          @click="()=>{components=item.key}">设置
                </n-button>
              </div>
            </div>
          </n-card>
        </n-grid-item>
      </template>
    </n-grid>
    <component
        :is="currentComponent"
        @close="()=>{components=null}"/>
  </div>
</template>

<style scoped lang="scss">

</style>
